import { userLogin, logout, getUserInfo } from '@/api/administrator'
import { getToken, setToken, removeToken } from '@/utils/auth'

const tokenKeyName = 'Authorization'
const user = {
  state: {
    userInfo: null,
    token: getToken(),
    avatar: ''
  },
  // console.log("roles")
  getters: {
    token: state => state.token,
    roles: state => state.roles,
    avatar: state => state.avatar
  },
  mutations: {
    SET_USERINFO: (state, userInfo) => {
      state.userInfo = userInfo
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_ROLES: (state, roles) => {
      state.roles = [roles]
    },
  },
  actions: {
    // 用户名登录
    async userLogin({ commit }, userInfo) {
      let res
      try {
        res = await userLogin(userInfo)
        if (res.code === 1) {  
          commit('SET_TOKEN', res.data)
          setToken(res.data)

        }
        return res
      } catch (error) {
        return Promise.reject(error)
      }
    },

    // 获取用户信息
    async getUserInfo({ commit, state }) {
      let res
      try {
        res = await getUserInfo(state.token)
        console.log("roles")
        console.log(res)
        if (res.code === 1) {
          commit('SET_USERINFO', res.data)
          commit('SET_ROLES', res.data.managerType)
          
        }
        return res
      } catch (error) {
        return Promise.reject(error)
      }
    },
    // 登出
    async LogOut({ commit }) {
      let res
      try {
        res = await logout()
        commit('SET_TOKEN', '')
        removeToken()
        return res
      } catch (error) {
        return Promise.reject(error)
      }
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    }
  }
}

export default user
